import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
import duration from 'dayjs/plugin/duration'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'

// 配置dayjs
dayjs.locale('zh-cn')
dayjs.extend(relativeTime)
dayjs.extend(duration)
dayjs.extend(utc)
dayjs.extend(timezone)

/**
 * 时间格式化工具
 */
export const timeUtils = {
  // 格式化时间
  format(time, format = 'YYYY-MM-DD HH:mm:ss') {
    return dayjs(time).format(format)
  },
  
  // 相对时间
  fromNow(time) {
    return dayjs(time).fromNow()
  },
  
  // 时间差
  diff(time1, time2, unit = 'minute') {
    return dayjs(time1).diff(dayjs(time2), unit)
  },
  
  // 获取时间范围
  getTimeRange(hours) {
    const end = dayjs()
    const start = end.subtract(hours, 'hour')
    return {
      start: start.toISOString(),
      end: end.toISOString()
    }
  },
  
  // 获取今天的时间范围
  getTodayRange() {
    const start = dayjs().startOf('day')
    const end = dayjs().endOf('day')
    return {
      start: start.toISOString(),
      end: end.toISOString()
    }
  },
  
  // 获取本周的时间范围
  getWeekRange() {
    const start = dayjs().startOf('week')
    const end = dayjs().endOf('week')
    return {
      start: start.toISOString(),
      end: end.toISOString()
    }
  },
  
  // 获取本月的时间范围
  getMonthRange() {
    const start = dayjs().startOf('month')
    const end = dayjs().endOf('month')
    return {
      start: start.toISOString(),
      end: end.toISOString()
    }
  },
  
  // 时间戳转换
  timestamp(time) {
    return dayjs(time).valueOf()
  },
  
  // 持续时间格式化
  formatDuration(milliseconds) {
    const duration = dayjs.duration(milliseconds)
    const days = duration.days()
    const hours = duration.hours()
    const minutes = duration.minutes()
    const seconds = duration.seconds()
    
    if (days > 0) {
      return `${days}天${hours}小时${minutes}分钟`
    } else if (hours > 0) {
      return `${hours}小时${minutes}分钟`
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds}秒`
    } else {
      return `${seconds}秒`
    }
  }
}

/**
 * 数字格式化工具
 */
export const numberUtils = {
  // 格式化数字
  format(num, decimals = 2) {
    if (isNaN(num)) return '--'
    return parseFloat(num).toFixed(decimals)
  },
  
  // 格式化百分比
  formatPercent(num, decimals = 1) {
    if (isNaN(num)) return '--'
    return `${parseFloat(num).toFixed(decimals)}%`
  },
  
  // 格式化文件大小
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  },
  
  // 千分位分隔符
  formatThousands(num) {
    if (isNaN(num)) return '--'
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  },
  
  // 数字范围检查
  inRange(num, min, max) {
    return num >= min && num <= max
  },
  
  // 生成随机数
  random(min = 0, max = 100, decimals = 0) {
    const num = Math.random() * (max - min) + min
    return parseFloat(num.toFixed(decimals))
  }
}

/**
 * 颜色工具
 */
export const colorUtils = {
  // 根据数值获取颜色
  getColorByValue(value, ranges) {
    for (const range of ranges) {
      if (value >= range.min && value <= range.max) {
        return range.color
      }
    }
    return '#999999'
  },
  
  // 温度颜色
  getTemperatureColor(temp) {
    const ranges = [
      { min: -50, max: 0, color: '#1890ff' },   // 蓝色 - 极冷
      { min: 0, max: 10, color: '#52c41a' },    // 绿色 - 冷
      { min: 10, max: 25, color: '#faad14' },   // 橙色 - 适中
      { min: 25, max: 35, color: '#fa8c16' },   // 深橙 - 热
      { min: 35, max: 100, color: '#f5222d' }   // 红色 - 极热
    ]
    return this.getColorByValue(temp, ranges)
  },
  
  // 湿度颜色
  getHumidityColor(humidity) {
    const ranges = [
      { min: 0, max: 30, color: '#fa8c16' },    // 橙色 - 干燥
      { min: 30, max: 60, color: '#52c41a' },   // 绿色 - 适中
      { min: 60, max: 80, color: '#1890ff' },   // 蓝色 - 湿润
      { min: 80, max: 100, color: '#722ed1' }   // 紫色 - 潮湿
    ]
    return this.getColorByValue(humidity, ranges)
  },
  
  // 气压颜色
  getPressureColor(pressure) {
    const ranges = [
      { min: 0, max: 95000, color: '#f5222d' },     // 红色 - 低压
      { min: 95000, max: 100000, color: '#fa8c16' }, // 橙色 - 较低
      { min: 100000, max: 103000, color: '#52c41a' }, // 绿色 - 正常
      { min: 103000, max: 106000, color: '#1890ff' }, // 蓝色 - 较高
      { min: 106000, max: 200000, color: '#722ed1' }  // 紫色 - 高压
    ]
    return this.getColorByValue(pressure, ranges)
  },
  
  // 光照强度颜色
  getLightColor(light) {
    const ranges = [
      { min: 0, max: 50, color: '#434343' },      // 深灰 - 黑暗
      { min: 50, max: 200, color: '#722ed1' },    // 紫色 - 昏暗
      { min: 200, max: 500, color: '#1890ff' },   // 蓝色 - 室内
      { min: 500, max: 1000, color: '#52c41a' },  // 绿色 - 明亮
      { min: 1000, max: 2000, color: '#faad14' }  // 黄色 - 强光
    ]
    return this.getColorByValue(light, ranges)
  },
  
  // 环境质量颜色
  getQualityColor(quality) {
    const colors = {
      EXCELLENT: '#52c41a',  // 绿色
      GOOD: '#1890ff',       // 蓝色
      FAIR: '#faad14',       // 橙色
      POOR: '#f5222d'        // 红色
    }
    return colors[quality] || '#999999'
  },
  
  // 趋势颜色
  getTrendColor(trend) {
    const colors = {
      RISING: '#f5222d',      // 红色 - 上升
      FALLING: '#1890ff',     // 蓝色 - 下降
      STABLE: '#52c41a',      // 绿色 - 稳定
      FLUCTUATING: '#faad14'  // 橙色 - 波动
    }
    return colors[trend] || '#999999'
  },
  
  // 十六进制转RGB
  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  },
  
  // RGB转十六进制
  rgbToHex(r, g, b) {
    return '#' + [r, g, b].map(x => {
      const hex = x.toString(16)
      return hex.length === 1 ? '0' + hex : hex
    }).join('')
  },
  
  // 颜色透明度
  addAlpha(color, alpha) {
    const rgb = this.hexToRgb(color)
    if (!rgb) return color
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`
  }
}

/**
 * 存储工具
 */
export const storageUtils = {
  // 设置localStorage
  setLocal(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (error) {
      console.error('设置localStorage失败:', error)
    }
  },
  
  // 获取localStorage
  getLocal(key, defaultValue = null) {
    try {
      const value = localStorage.getItem(key)
      return value ? JSON.parse(value) : defaultValue
    } catch (error) {
      console.error('获取localStorage失败:', error)
      return defaultValue
    }
  },
  
  // 删除localStorage
  removeLocal(key) {
    try {
      localStorage.removeItem(key)
    } catch (error) {
      console.error('删除localStorage失败:', error)
    }
  },
  
  // 清空localStorage
  clearLocal() {
    try {
      localStorage.clear()
    } catch (error) {
      console.error('清空localStorage失败:', error)
    }
  },
  
  // 设置sessionStorage
  setSession(key, value) {
    try {
      sessionStorage.setItem(key, JSON.stringify(value))
    } catch (error) {
      console.error('设置sessionStorage失败:', error)
    }
  },
  
  // 获取sessionStorage
  getSession(key, defaultValue = null) {
    try {
      const value = sessionStorage.getItem(key)
      return value ? JSON.parse(value) : defaultValue
    } catch (error) {
      console.error('获取sessionStorage失败:', error)
      return defaultValue
    }
  },
  
  // 删除sessionStorage
  removeSession(key) {
    try {
      sessionStorage.removeItem(key)
    } catch (error) {
      console.error('删除sessionStorage失败:', error)
    }
  }
}

/**
 * 防抖和节流
 */
export const throttleUtils = {
  // 防抖
  debounce(func, wait, immediate = false) {
    let timeout
    return function executedFunction(...args) {
      const later = () => {
        timeout = null
        if (!immediate) func(...args)
      }
      const callNow = immediate && !timeout
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) func(...args)
    }
  },
  
  // 节流
  throttle(func, limit) {
    let inThrottle
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  }
}

/**
 * 数据验证工具
 */
export const validateUtils = {
  // 邮箱验证
  isEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return re.test(email)
  },
  
  // 手机号验证
  isPhone(phone) {
    const re = /^1[3-9]\d{9}$/
    return re.test(phone)
  },
  
  // URL验证
  isUrl(url) {
    try {
      new URL(url)
      return true
    } catch {
      return false
    }
  },
  
  // IP地址验证
  isIP(ip) {
    const re = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
    return re.test(ip)
  },
  
  // 身份证验证
  isIdCard(idCard) {
    const re = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    return re.test(idCard)
  },
  
  // 密码强度验证
  checkPasswordStrength(password) {
    let score = 0
    const checks = {
      length: password.length >= 8,
      lowercase: /[a-z]/.test(password),
      uppercase: /[A-Z]/.test(password),
      number: /\d/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
    }
    
    Object.values(checks).forEach(check => {
      if (check) score++
    })
    
    let strength = 'weak'
    if (score >= 4) strength = 'strong'
    else if (score >= 3) strength = 'medium'
    
    return { score, strength, checks }
  }
}

/**
 * 文件工具
 */
export const fileUtils = {
  // 下载文件
  download(data, filename, type = 'application/octet-stream') {
    const blob = new Blob([data], { type })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  },
  
  // 读取文件
  readFile(file, type = 'text') {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = e => resolve(e.target.result)
      reader.onerror = reject
      
      switch (type) {
        case 'text':
          reader.readAsText(file)
          break
        case 'dataURL':
          reader.readAsDataURL(file)
          break
        case 'arrayBuffer':
          reader.readAsArrayBuffer(file)
          break
        default:
          reader.readAsText(file)
      }
    })
  },
  
  // 获取文件扩展名
  getExtension(filename) {
    return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
  },
  
  // 检查文件类型
  checkFileType(file, allowedTypes) {
    const extension = this.getExtension(file.name).toLowerCase()
    return allowedTypes.includes(extension)
  },
  
  // 检查文件大小
  checkFileSize(file, maxSize) {
    return file.size <= maxSize
  }
}

/**
 * URL工具
 */
export const urlUtils = {
  // 获取URL参数
  getParams(url = window.location.href) {
    const params = {}
    const urlObj = new URL(url)
    urlObj.searchParams.forEach((value, key) => {
      params[key] = value
    })
    return params
  },
  
  // 设置URL参数
  setParams(params, url = window.location.href) {
    const urlObj = new URL(url)
    Object.entries(params).forEach(([key, value]) => {
      if (value !== null && value !== undefined) {
        urlObj.searchParams.set(key, value)
      } else {
        urlObj.searchParams.delete(key)
      }
    })
    return urlObj.toString()
  },
  
  // 删除URL参数
  removeParams(keys, url = window.location.href) {
    const urlObj = new URL(url)
    keys.forEach(key => {
      urlObj.searchParams.delete(key)
    })
    return urlObj.toString()
  }
}

/**
 * 设备检测工具
 */
export const deviceUtils = {
  // 检测是否为移动设备
  isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  },
  
  // 检测是否为平板
  isTablet() {
    return /iPad|Android(?!.*Mobile)/i.test(navigator.userAgent)
  },
  
  // 检测是否为桌面设备
  isDesktop() {
    return !this.isMobile() && !this.isTablet()
  },
  
  // 获取设备类型
  getDeviceType() {
    if (this.isMobile()) return 'mobile'
    if (this.isTablet()) return 'tablet'
    return 'desktop'
  },
  
  // 获取浏览器信息
  getBrowserInfo() {
    const ua = navigator.userAgent
    let browser = 'Unknown'
    
    if (ua.includes('Chrome')) browser = 'Chrome'
    else if (ua.includes('Firefox')) browser = 'Firefox'
    else if (ua.includes('Safari')) browser = 'Safari'
    else if (ua.includes('Edge')) browser = 'Edge'
    else if (ua.includes('Opera')) browser = 'Opera'
    
    return {
      browser,
      userAgent: ua,
      language: navigator.language,
      platform: navigator.platform
    }
  }
}

// 数据验证工具
export const dataUtils = {
  // 验证传感器数据是否有效
  validateSensorData: (data) => {
    if (!data) return false
    
    // 判断数据类型：原始数据、小时聚合、日聚合、月聚合
    const isHourlyData = data.hour !== undefined || data.avgTemp !== undefined
    const isDailyData = data.date !== undefined
    const isMonthlyData = data.month !== undefined
    const isAggregatedData = isHourlyData || isDailyData || isMonthlyData
    
    console.log('数据类型检测:', { 
      isHourlyData, 
      isDailyData, 
      isMonthlyData, 
      isAggregatedData 
    })
    
    // 针对不同类型数据进行验证
    if (isAggregatedData) {
      // 聚合数据验证
      
      // 检查时间字段
      if (isHourlyData && !data.hour) {
        console.warn('聚合数据验证失败: 缺少小时字段', data)
        return false
      }
      
      if (isDailyData && !data.date) {
        console.warn('聚合数据验证失败: 缺少日期字段', data)
        return false
      }
      
      if (isMonthlyData && !data.month) {
        console.warn('聚合数据验证失败: 缺少月份字段', data)
        return false
      }
      
      // 检查数值字段
      const tempField = data.avgTemperature !== undefined ? 'avgTemperature' : 'avgTemp'
      const humidityField = 'avgHumidity'
      const pressureField = data.avgPressure !== undefined ? 'avgPressure' : 'avgPress'
      const lightField = data.avgLightIntensity !== undefined ? 'avgLightIntensity' : 'avgLight'
      
      // 只要有一个字段存在即可
      if (data[tempField] === undefined && 
          data[humidityField] === undefined && 
          data[pressureField] === undefined && 
          data[lightField] === undefined) {
        console.warn('聚合数据验证失败: 缺少数值字段', data)
        return false
      }
      
      return true
    } else {
      // 原始数据验证
      // 检查必要字段是否存在
      const requiredFields = ['temperature', 'humidity', 'pressure', 'lightIntensity']
      const timeField = data.createdAt !== undefined ? 'createdAt' : 'time'
      
      if (data[timeField] === undefined) {
        console.warn(`数据验证失败: 缺少时间字段 ${timeField}`, data)
        return false
      }
      
      // 至少有一个传感器数据字段
      const hasAnyField = requiredFields.some(field => data[field] !== undefined)
      if (!hasAnyField) {
        console.warn('数据验证失败: 缺少所有传感器数据字段', data)
        return false
      }
      
      return true
    }
  },
  
  // 验证数据集合
  validateDataset: (dataArray) => {
    if (!Array.isArray(dataArray)) {
      console.warn('数据集验证失败: 不是数组')
      return false
    }
    
    if (dataArray.length === 0) {
      console.warn('数据集验证失败: 空数组')
      return false
    }
    
    // 检查第一条数据，判断数据类型
    const firstItem = dataArray[0]
    console.log('数据集首项:', firstItem)
    
    // 判断数据类型
    const isHourlyData = firstItem.hour !== undefined || firstItem.avgTemp !== undefined
    const isDailyData = firstItem.date !== undefined
    const isMonthlyData = firstItem.month !== undefined
    const isAggregatedData = isHourlyData || isDailyData || isMonthlyData
    
    console.log('数据集类型:', { 
      isHourlyData, 
      isDailyData, 
      isMonthlyData, 
      isAggregatedData,
      length: dataArray.length
    })
    
    // 对于聚合数据，简化验证，只要数组不为空即可
    if (isAggregatedData) {
      return true
    }
    
    // 对于原始数据，检查每个数据项
    const validItems = dataArray.filter(item => dataUtils.validateSensorData(item))
    console.log(`数据集验证: 共${dataArray.length}条数据，有效数据${validItems.length}条`)
    
    return validItems.length > 0
  },
  
  // 格式化数据，确保所有字段类型正确
  formatSensorData: (data) => {
    if (!data) return null
    
    return {
      id: data.id,
      temperature: parseFloat(data.temperature),
      humidity: parseFloat(data.humidity),
      pressure: parseFloat(data.pressure),
      lightIntensity: parseInt(data.lightIntensity),
      createdAt: data.createdAt,
      updatedAt: data.updatedAt
    }
  },
  
  // 格式化数据集合
  formatDataset: (dataArray) => {
    if (!Array.isArray(dataArray)) return []
    return dataArray.map(item => dataUtils.formatSensorData(item)).filter(Boolean)
  }
}

// 默认导出所有工具
export default {
  timeUtils,
  numberUtils,
  colorUtils,
  storageUtils,
  throttleUtils,
  validateUtils,
  fileUtils,
  urlUtils,
  deviceUtils,
  dataUtils
}